package com.lgc.leetcode.medium.threeSumClosest16;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Program {
    public static void main(String[] args) {
        //给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数，使得它们的和与 target 最接近。
        // 返回这三个数的和。假定每组输入只存在唯一答案。
        //
        //例如，给定数组 nums = [-1，2，1，-4], 和 target = 1.
        //与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

        Program program = new Program();
        int[] nums = {1,2,5,10,11};
        int aa = program.threeSumClosest(nums, 12);

        int a = 0;
    }

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];

        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (Math.abs(sum - target) < Math.abs(result - target)) { //求最接近的
                    result = sum;
                }

                if (sum < target) {
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    left++;
                } else if (sum > target) {
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    right--;
                } else {
                    return sum;
                }
            }
        }

        return result;
    }

    public int threeSumClosest2(int[] nums, int target) {

        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int threeSum = nums[left] + nums[right] + nums[i];
                if (Math.abs(threeSum - target) < Math.abs(result - target)) {
                    result = threeSum;
                }
                if (threeSum > target) {
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    right--;
                } else if (threeSum < target) {
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    left++;
                } else {
                    // 如果已经等于target的话, 肯定是最接近的
                    return target;
                }

            }

        }

        return result;
    }
}
